// 新闻动态-新闻列表
import React from 'react';
import { observer, useLocalStore } from 'mobx-react-lite';
import { Link } from 'react-router-dom';
import { Form, DatePicker, Button, Input, Card, Row, Col, Pagination, message, Modal } from 'antd';
import { SearchOutlined, PlusSquareOutlined } from '@ant-design/icons';
import moment from 'moment';
import * as listApi from '~/apis/news/listApi';
import AjaxSelect from '~/components/AjaxSelect';
import { config } from '~/config/config';
import '~/styles/news.local.sass';

// 声明顶部SearchForm组件
const { RangePicker } = DatePicker;
const FormItem = Form.Item;

const showTotal = (total: number) => `Total: ${total}`;

const cardConfig = {
  size: 'small' as const,
  bordered: false,
};

const formItemLayout = {
  labelCol: { span: 4 },
  wrapperCol: { span: 20 },
};


const MyNewsList = observer(() => {
  const state = useLocalStore(() => ({
    loading: false,
    tableList: {
      data: [],
      pageNo: 1,
      pageSize: 8,
      totalCount: 0,
      totalPage: 0,
    },
    getData: {} as any,
  }));

  const [form] = Form.useForm();
  const doQuery = (curPage: number = 1) => {
    state.tableList.pageNo = curPage;
    const { pageNo, pageSize } = state.tableList;

    // 时间戳处理
    const { time } = state.getData;
    let startTime = null;
    let endTime = null;
    if (time && time.length > 0) {
      startTime = new Date(time[0]).getTime();
      endTime = new Date(time[1]).getTime();
    }

    const params = {
      pageNum: pageNo,
      pageSize,
      startTime,
      endTime,
      ...state.getData,
    };

    delete params.time;
    state.loading = true;

    listApi.getMyNewsList(params).then((res) => {
      state.tableList = {
        ...state.tableList,
        data: res.data,
        totalCount: res.pageInfo.total,
        totalPage: res.pageInfo.totalPages,
      };
    }).finally(() => {
      state.loading = false;
    });
  };

  const onSearch = (values: any) => {
    state.getData = values;
    doQuery(1);
  };

  const onReset = () => {
    form.resetFields();
  };

  const { confirm } = Modal;
  //   const columns = getColumns(ProjectList);
  // 删除
  const deleteItem = (id: number | string) => {
    confirm({
      title: 'Do you want to delete this news?',
      onOk() {
        listApi.handleNewsDelete(id).then(() => {
          message.success('delete success');
          doQuery(1);
        });
      },
    });
  };

  //   const columns = getColumns(ProjectList);

  const { loading,
    tableList: {
      pageNo, totalCount, pageSize, data,
    } } = state;

  const tableOption: any = {
    loading,
    // columns,
    pagination: {
      current: pageNo,
      total: totalCount,
      pageSize,
      size: 'small',
      showQuickJumper: true,
      showTotal,
      onChange: (curPage: number) => {
        doQuery(curPage);
      },
    },
    dataSource: data || [],
    rowKey: 'id',
    size: 'small',
  };


  React.useEffect(() => {
    doQuery(1);
  }, []);

  // 项目列表渲染
  const imgUrl = config.ossUrl;
  const myNewsList = tableOption.dataSource;
  const myNewsListItems: any = [];
  const auditStatusList = ['Reviewing', '', 'Rejected']; // 新闻审核状态列表 | 审核状态 0 未审核 /1 审核通过 /2审核拒绝
  myNewsList.forEach((item: any) => {
    myNewsListItems.push(
      <li key={item.id}>
        <Link to={`/news/details?id=${item.id as string}`} >
          <div className="list-container">
            <span className="avatar">
              {
                (() => {
                  if (item.mainPicUrl) {
                    return (<img src={`${imgUrl}${item.mainPicUrl as string}`} alt='' className="avatar-img"/>);
                  }
                  return <></>;
                })()
              }
            </span>
            <div className="news-content">
              <div className="news-title">
                <h3>{item.title}</h3>
              </div>
              <p className="h-48 truncate">{item.summary}</p>
              <div className="news-detail">
                <p>{item.countryName}</p>
                <p>{moment(item.createTime).format('YYYY/MM/DD')}</p>
              </div>
            </div>
          </div>
        </Link>

        <div className="bottom-tag">
          <button><Link to={`/news/edit?id=${item.id as string}`}>Edit</Link></button>
          <button><Link to={`/news/details?id=${item.id as string}`}>View</Link></button>
          <button onClick={() => deleteItem(item.id)}>Delete</button>
        </div>
        <div className="top-tag">
          <p className={auditStatusList[item.auditStatus]}>{auditStatusList[item.auditStatus]}</p>
        </div>
      </li>,
    );
  });

  return (
    <div>
      {/* 顶部搜索栏 */}
      <div className="news-search">
        <Card {...cardConfig} className="search-card">
          <Form form={form} onFinish={onSearch}>
            <Row>
              <Col span={4}>
                <Form.Item name="time" {...formItemLayout}>
                  <RangePicker
                    format="YYYY-MM-DD"
                    placeholder={['Start Time', 'End Time']}
                    style={{ width: '100%' }}
                  />
                </Form.Item>
              </Col>
              <Col span={4}>
                <Form.Item name="countryId" shouldUpdate={true} {...formItemLayout}
                >
                  <AjaxSelect
                    placeholder="Country/Region"
                    type="countryList"
                  />
                </Form.Item>
              </Col>
              <Col span={4}>
                <FormItem name="projectName" {...formItemLayout} >
                  <Input
                    allowClear={true}
                    onPressEnter={onSearch}
                    prefix={
                      <SearchOutlined style={{ color: '#A9B8CF' }}/>
                    }
                  />
                </FormItem>
              </Col>
              <Col span={2}>
                <FormItem {...formItemLayout}>
                  <Button
                    type="primary"
                    htmlType="submit"
                    className="mr-2"
                    block
                  >
                                Search
                  </Button>
                </FormItem>
              </Col>
              <Col span={2}>
                <FormItem {...formItemLayout}>
                  <Button className="mr-2" onClick={onReset} block>
                                Reset
                  </Button>
                </FormItem>
              </Col>
            </Row>
          </Form>
        </Card>
      </div>

      <div className="news-list">
        <ul >
          <li className="new-news">
            <Link to={'/news/add'}>
              <div>
                <PlusSquareOutlined style={{ fontSize: '32px', color: '#9DAFCC', marginTop: '2px' }} />
              </div>
            </Link>
            <p>New news</p>
          </li>
          {myNewsListItems}
        </ul>
      </div>

      <div>
        <Pagination
          showQuickJumper
          defaultCurrent={1}
          total={tableOption.pagination.total}
          showTotal={(total) => `Total ${total}`}
          pageSize={8}
          onChange={tableOption.pagination.onChange} />
      </div>
    </div>
  );
});

export default MyNewsList;
